<template>
  <div>
    <el-form ref="form" label-width="80px">
      <el-form-item label="SPU名称">
        <el-input placeholder="spu名称" v-model="spuData.spuName"></el-input>
      </el-form-item>
      <!-- 品牌选择 -->
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spuData.tmId">
          <el-option
            v-for="(item, index) in TrademarkList"
            :key="index"
            :value="item.id"
            :label="item.tmName"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 描述 -->
      <el-form-item label="spu描述">
        <el-input
          type="textarea"
          placeholder="描述"
          v-model="spuData.description"
        ></el-input>
      </el-form-item>
      <!-- 照片墙 -->
      <el-form-item label="label">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="imageList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="upImage"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <!-- 销售属性表格 -->
      <el-form-item label="销售属性">
        <el-select
          :placeholder="`还有${unAttrList.length}未选择`"
          v-model="attrInfo"
        >
          <el-option
            v-for="(item, index) in unAttrList"
            :value="`${item.id}:${item.name}`"
            :key="index"
            :label="item.name"
          >
          </el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!attrInfo"
          @click="addSaleAttr()"
          >添加销售属性</el-button
        >
        <el-table border style="width: 100%" :data="spuData.spuSaleAttrList">
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            prop="saleAttrName"
            label="属性名"
            width="200"
          >
          </el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            prop=""
            label="属性名称列表"
            ><template slot-scope="{ row }">
              <el-tag
                :key="tag.id"
                v-for="(tag, index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="handleClose(index, row)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
                >添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            prop="prop"
            label="操作"
            width="200"
            ><template slot-scope="{ $index }">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="spuData.spuSaleAttrList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <!-- 保存操作 -->
      <el-form-item>
        <el-button type="primary" @click="addOrupdateSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      attrInfo: "", // 选择添加属性的信息
      //spu信息
      spuData: {
        category3Id: 0, // 三级分类id
        description: "", // 描述
        id: null,
        spuImageList: [
          // spu图片信息
          // {
          //   id: 0,
          //   imgName: "string",
          //   imgUrl: "string",
          //   spuId: 0,
          // },
        ],
        spuName: "", // spu名称
        spuSaleAttrList: [
          // 平台属性值
          // {
          //   baseSaleAttrId: 0,
          //   id: 0,
          //   saleAttrName: "string",
          //   spuId: 0,
          //   spuSaleAttrValueList: [
          //     {
          //       baseSaleAttrId: 0,
          //       id: 0,
          //       isChecked: "string",
          //       saleAttrName: "string",
          //       saleAttrValueName: "string",
          //       spuId: 0,
          //     },
          //   ],
          // },
        ],
        tmId: null, // 品牌id
      },
      TrademarkList: [], // 品牌信息
      AttrList: [], // 售卖属性
      imageList: [], // 照片墙
    };
  },
  methods: {
    //  删除照片墙触发
    handleRemove(file, fileList) {
      // file:删除的图 fileList：剩余的图
      console.log(file, fileList);
    },
    // 查看照片墙图片触发
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 图片上传成功时
    upImage(response, file, fileList) {
      // 处理数据格式
      file.imgName = file.name;
      file.imgUrl = response.data;
      this.imageList.push(file);
    },
    // 获取品牌列表和销售属性
    async getMarkList(id) {
      this.spuData.category3Id = id;
      let resTrademark = await this.$API.spu.reqTrademarkList();
      if (resTrademark.code == 200) {
        this.TrademarkList = resTrademark.data;
      }

      let resAttrList = await this.$API.spu.reqSaleAttrList();
      if (resAttrList.code == 200) {
        this.AttrList = resAttrList.data;
      }
    },
    // 发请求，获取需要的数据
    async getData(row) {
      this.getMarkList();
      // 获取spu数据
      let spuRes = await this.$API.spu.reqSpuById(row.id);
      if (spuRes.code == 200) {
        this.spuData = spuRes.data;
      }

      let resImageList = await this.$API.spu.reqSouImageList(row.id);
      if (resImageList.code == 200) {
        this.imageList = resImageList.data;
        // 对数据字段进行处理，照片墙要有name，和url字段才能显示
        this.imageList.forEach((item) => {
          item.url = item.imgUrl;
          item.name = item.imgName;
        });
      }
    },
    // 添加属性信息
    addSaleAttr() {
      const [baseSaleAttrId, saleAttrName] = this.attrInfo.split(":");
      let obj = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] };
      this.spuData.spuSaleAttrList.push(obj);
      this.attrInfo = "";
    },
    // 每个销售属性都应该有自己的一个变量去控制输入框和添加按钮的显示和隐藏
    // 点击添加按钮的回调
    showInput(row) {
      // 给销售属性添加一个响应式数据控制显示和隐藏
      this.$set(row, "inputVisible", true);
      // 添加一个字段用于收集input输入内容
      this.$set(row, "inputValue", "");
    },
    // input失去焦点或按下回车时
    handleInputConfirm(row) {
      // 将收集到的数据放到展示的数组里面
      const { baseSaleAttrId, inputValue } = row;
      // 判断输入是否为空
      if (inputValue.trim() == "") {
        this.$message({
          type: "warning",
          message: "属性值不能为空",
        });
        return;
      }
      // 判断添加属性值是否重复
      let res = row.spuSaleAttrValueList.every((item) => {
        return item.saleAttrValueName != inputValue;
      });
      if (res) {
        let newsaleAttrValue = {
          baseSaleAttrId,
          saleAttrValueName: inputValue,
        };
        row.spuSaleAttrValueList.push(newsaleAttrValue);
        row.inputVisible = false;
      } else {
        this.$message({
          type: "warning",
          message: "不能添加重复内容",
        });
      }
    },
    // 删除标签
    handleClose(index, row) {
      row.spuSaleAttrValueList.splice(index, 1);
    },
    // 保存按钮
    async addOrupdateSpu() {
      // 整理参数
      this.spuData.spuImageList = this.imageList;
      let res = await this.$API.spu.reqSaveSpu(this.spuData);
      if (res.code == 200) {
        this.$message({
          type: "success",
          message: "操作成功",
        });
        // 触发自定义事件回到列表页
        this.$emit("changeScene", {
          scene: "01",
          flag: this.spuData.id ? "修改" : "添加",
        });

        // 清空spuData数据
        // Object.assign是es6新增的方法可以合并对象
        // this._data可以操控data中的响应式数据
        // this.$options可以获取当前配置对象
        Object.assign(this._data, this.$options.data());
      }
    },
    // 取消按钮
    cancel() {
      this.$emit("changeScene", {
        scene: "02",
        flag: this.spuData.id ? "修改" : "添加",
      });
      Object.assign(this._data, this.$options.data());
    },
  },
  computed: {
    // 计算出所有还未被添加的销售属性
    unAttrList() {
      return this.AttrList.filter((item) => {
        return this.spuData.spuSaleAttrList.every((item1) => {
          return item.name != item1.saleAttrName;
        });
      });
    },
  },
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>